<template>
  <form-item-wrapper :designer="designer" :field="field" :rules="rules" :design-state="designState"
    :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId">
    <personSelect ref="personSelectRef" v-show="!(isReadMode || field.options.readonly)" v-model:modelValue="field.options.defaultValue" :placeholder="field.options.placeholder"
      :modelValue="field.options.defaultValue" :multiple="field.options.multiple" :clearable="field.options.clearable"
      title="人员选择" :authorityList="field.options.authorityList" :disabled="isReadMode || field.options.readonly || field.options?.isAllowEditSelectorField == '2'" @change="onUserUpdate"
      :selectType="field.options.selectType" :choosePerson="field.options.choosePerson" :organizeType="field.options.organizeType"
      :displayFormat="field.options.displayFormat" :comUse="''" :isReturnData="field.options.isReturnData" :isAutoImport="field.options.isAutoImport"
      :isAutoSortOrder="field.options.isAutoSortOrder"/>
    <template v-if="isReadMode || field.options.readonly">
      <span class="readonly-mode-field">{{ (this.$refs.personSelectRef && this.$refs.personSelectRef.$refs.commonSelectRef) && (this.$refs.personSelectRef.$refs.commonSelectRef.innerValue || this.$refs.personSelectRef.$refs.commonSelectRef.tagsList.toString()) }}</span>
    </template>
  </form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import i18n, { translate } from "@/utils/i18n";
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";
import { generateId } from "@/utils/util";
import personSelect from "@/components/ZHLX-Components/ZHLX-personSelect/index.vue";
import { getDeptList } from "@/api/admin/dept";

export default {
  name: "select-person-widget",
  componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    },

  },
  inject: ['refList'],
  components: {
    FormItemWrapper,
    personSelect,
  },
  data() {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: [],
      widgetKey: '',
      isRefresh: false,
    }
  },
  watch: {
    // 'field.options.readonly': {
    //   deep: true,
    //   handler() {
    //     this.autoImportUserInfo()
    //   }
    // } 
    isRefresh: {
      handler() {
        this.autoImportUserInfo()
      }
    }
  },
  computed: {
    allowDefaultFirstOption() {
      return !!this.field.options.filterable || !!this.field.options.remote
    },

    remoteMethod() {
      if (!!this.field.options.remote && !!this.field.options.onRemoteQuery) {
        return this.remoteQuery
      } else {
        return undefined
      }
    },

    selectKey() {
      return this.widgetKey || this.field.id
    },
    
    // 获取关联该选人组件的部门组件
    linkageWidgets() {
      const list = []
      Object.keys(this.refList).forEach(refItem => {
        const field = this.refList[refItem]?.field
        if (field && field.options && field.options.openLinkageWidget && field.options.linkageWidget == this.field?.options?.name) {
          list.push({
            key: refItem,
            data: field
          })
        }
      })
      return list
    }
  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */
    this.registerToRefList()
    this.initOptionItems()
    this.initFieldModel()
    this.initEventHandler()
    this.buildFieldRules()

    this.handleOnCreated()
    // setTimeout(() => {
    //   this.autoImportUserInfo()
    // }, 1000);
  },

  mounted() {
    this.handleOnMounted()
  },

  beforeUnmount() {
    this.unregisterFromRefList()
  },

  methods: {
    /**
     * 获取选中项label
     * @return {*}
     */
    getSelectedLabel() {
      return this.$refs.fieldEditor.selectedLabel
    },

    refreshWidgetKey() {  //强制刷新组件！！
      this.widgetKey = 'select-key-' + generateId()
    },
    /**
     * 自动导入用户信息
       * 只读：
       *  1.有值 展示值
       *  2.无值 展示空字符串
       * 编辑：
       *  1.有值 展示值
       *  2.无值 且开启自动引入 展示当前用户信息
     * @returns 无返回值
     */
    autoImportUserInfo() {
      if (!this.designState) {
        if (!this.field.options.readonly) {
          // 编辑
          if (!this.field.options.defaultValue) {
            if (this.field.options.isAutoImport) {
              let userId = this.getGlobalDsv()['userInfo'].userId || ''
              this.field.options.defaultValue = userId
              this.syncUpdateFormModel(userId);
              this.dispatch('VFormRender', 'fieldValidation', [this.getPropName()])
              this.emitFieldDataChange(userId, "")
            }
          }
        }
      }
    },
    onUserUpdate(val, list) {
      // if (!val || !val.length) return
          // const selectData = this.comUse === 'vForm' ? formatData : deepClone(this.selectedIds);
          // this.$emit("update:modelValue", this.multiple ? selectData : selectData[0])
      const dataList = this.field.options.isReturnData ? list : val ;
      const value = this.field.options.multiple ? dataList : dataList[0];
      this.syncUpdateFormModel(value);
      this.emitFieldDataChange(list, [])
      this.field.options.defaultValue = value;
      this.dispatch('VFormRender', 'fieldValidation', [this.getPropName()])

      // 如果开启自动获取对应部门、并且存在关联部门组件，则自动获取对应部门
      if (this.field.options.personnelDepartmentLinkage && this.field.options.relatedDepartmentWidgets) {
        this.automaticReplenishmentDept(list)
      }
      
      if(this.linkageWidgets?.length) {
        this.automaticReplenishmentDept(list)
      }
    },
    /**
     * @description: 自动补全部门列表
     * @param {Array} list - 需要匹配的部门ID列表
     * @description 该方法首先检查本地存储中是否存在部门列表，如果不存在则从服务器获取并存入本地存储。
     * 然后根据传入的部门ID列表筛选出匹配的部门信息，并更新相关UI组件。
     * @returns {void}
     * @Author: ZJP
     */    
    async automaticReplenishmentDept(list) {
      // 从本地存储中获取部门列表
      if(!this.allDeptList?.length) {
        this.allDeptList = JSON.parse(window.sessionStorage.getItem('zhlx_all_deptList'))
      }

      // 如果本地存储中不存在部门列表，则从服务器获取并存入本地存储
      if (!this.allDeptList?.length) {
        const res = await getDeptList()
        this.allDeptList = res.data
        window.sessionStorage.setItem('zhlx_all_deptList', JSON.stringify(res.data))
      }
      
      // 去重并转为数组
      const matchDeptIds = [...new Set(list.map(item => item.deptId))]

      // 从部门列表中筛选匹配的部门并根据实际情况补齐数据
      const matchDeptInfos = []
      for(let i=0; i<matchDeptIds.length; i++) {
        const findDept = this.allDeptList.find(item => item.deptId === matchDeptIds[i])
        if (findDept) {
          matchDeptInfos.push(Object.assign({}, findDept, {
            sort: 0, 
            children: null, 
            downFlag: false, 
            objectType: 'organize',
            mainName: findDept.name, 
            mainId: findDept.deptId, 
            id: findDept.deptId, 
          }))
        }
      }

      // 更新关联部门组件的数据 - 旧版，待废弃
      this.refList[this.field.options.relatedDepartmentWidgets]?.onUserUpdate(matchDeptIds, matchDeptInfos)
      // 更新关联部门组件的数据 - 新版
      this.linkageWidgets.forEach(item => {
        if (item.key.includes('@row')) {
          if(item.data.options.linkageAttribute === 'department' && item.key.includes(this.subFormRowId)) this.refList[item.key]?.onUserUpdate(matchDeptIds, matchDeptInfos)
        } else {
          if(item.data.options.linkageAttribute === 'department') this.refList[item.key]?.onUserUpdate(matchDeptIds, matchDeptInfos)
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/global.scss";
/* form-item-wrapper已引入，还需要重复引入吗？ */

.full-width-input {
  width: 100% !important;
}
</style>
